package com.example.service;

import com.example.mapper.OrderMapper;
import com.example.model.OrderInfo;
import com.example.model.OrderInfoP;
import com.example.model.ProductInfo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EurekaServiceInstance;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class OrderServiceEureka {
    @Autowired
    private OrderMapper orderMapper;
    @Resource
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;

    private List<ServiceInstance> instances;

    private AtomicInteger atomicInteger = new AtomicInteger();

    public OrderInfoP selectOrderByIdE(Integer orderId) {
        OrderInfo orderInfo = orderMapper.selectOrderById(orderId);
        //String url = "http://127.0.0.1:8081/product/" +orderInfo.getProductId();
        instances = discoveryClient.getInstances("product-service");
        int index = atomicInteger.getAndIncrement() % instances.size();
        EurekaServiceInstance instance = (EurekaServiceInstance) instances.get(index);
        //log.info(instances.toString());
        log.info(instance.getInstanceId());
        String url = instance.getUri() + "/product/" + orderInfo.getProductId();
        ProductInfo productInfo = restTemplate.getForObject(url,
                ProductInfo.class);
        OrderInfoP orderInfoP = new OrderInfoP(orderInfo);
        orderInfoP.setProductInfo(productInfo);
        return orderInfoP;
    }
}
